package com.apicloud.modulehttp;

import android.util.Log;

import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

import org.json.JSONException;
import org.json.JSONObject;


public class Dome extends UZModule {
    public Dome(UZWebView webView) {
        super(webView);
    }

    public void jsmethod_ajax(final UZModuleContext moduleContext)
    {
        final JSONObject res = new JSONObject();
        new Thread() {
            public void run() {
                try {
                    String url = moduleContext.optString("url");
                    JSONObject data = moduleContext.optJSONObject("data");
                    String charset = moduleContext.optString("charset", "utf-8");
                    int timeout = moduleContext.optInt("timeout", 30000);
                    JSONObject headers = moduleContext.optJSONObject("headers");

                    HttpClient.Response response = null;
                    HttpClient httpClient = new HttpClient(charset, timeout);

                    if(data==null) {
                        response = httpClient.get(url, headers);
                    }else {
                        response = httpClient.post(url, data, headers);
                    }
                    res.put("statusCode", response.code)
                            .put("headers", response.headers)
                            .put("body", response.body);
                    if(response.code == 200){
                        moduleContext.success(res);
                    }else{
                        moduleContext.error(res);
                    }
                } catch (Exception e) {
                    try {
                        res.put("statusCode", 500).put("message", e.getMessage());
                        moduleContext.error(res);
                    } catch (JSONException ex) { }
                }
            }
        }.start();
    }

}
